/**
 * TextureAtlas Class
 * 
 * A simplified implementation for handling texture atlases in DragonBones animations.
 */

import { TextureAtlasData, SubTextureData } from './types';
import { Logger } from '../../../utils/Logger';

export class TextureAtlas {
  public name: string;
  public imagePath: string;
  public subTextures: Map<string, SubTexture> = new Map();
  private atlasData: TextureAtlasData;
  private atlasImage: any = null; // Canvas Image

  constructor(name: string, atlasData: TextureAtlasData) {
    this.name = name;
    this.atlasData = atlasData;
    this.imagePath = atlasData.imagePath;
    
    const logger = Logger.getInstance();
    logger.log(`Creating texture atlas: ${this.name}`, 'TextureAtlas');
    
    // Create sub textures
    if (atlasData.SubTexture) {
      this.createSubTextures(atlasData.SubTexture);
    }
    
    logger.log(`Successfully created texture atlas: ${this.name} with ${this.subTextures.size} sub textures`, 'TextureAtlas');
  }

  /**
   * Creates sub textures from sub texture data
   * @param subTextureDataArray - Array of sub texture data
   */
  private createSubTextures(subTextureDataArray: SubTextureData[]): void {
    const logger = Logger.getInstance();
    logger.log(`Creating ${subTextureDataArray.length} sub textures`, 'TextureAtlas');
    
    for (const subTextureData of subTextureDataArray) {
      const subTexture: SubTexture = {
        name: subTextureData.name,
        x: subTextureData.x || 0,
        y: subTextureData.y || 0,
        width: subTextureData.width || 0,
        height: subTextureData.height || 0,
        frameX: subTextureData.frameX || 0,
        frameY: subTextureData.frameY || 0,
        frameWidth: subTextureData.frameWidth || subTextureData.width || 0,
        frameHeight: subTextureData.frameHeight || subTextureData.height || 0
      };
      
      this.subTextures.set(subTexture.name, subTexture);
      logger.log(`Created sub texture: ${subTexture.name}`, 'TextureAtlas');
    }
  }

  /**
   * Loads the atlas image
   * @param image - The loaded image (Canvas Image)
   */
  public loadAtlasImage(image: any): void {
    this.atlasImage = image;
  }

  /**
   * Gets a sub texture by name
   * @param name - The name of the sub texture
   * @returns The sub texture or null if not found
   */
  public getSubTexture(name: string): SubTexture | null {
    return this.subTextures.get(name) || null;
  }

  /**
   * Gets the atlas image
   * @returns The atlas image or null if not loaded
   */
  public getAtlasImage(): any {
    return this.atlasImage;
  }

  /**
   * Gets whether the atlas image is loaded
   * @returns True if the atlas image is loaded
   */
  public isLoaded(): boolean {
    return this.atlasImage !== null;
  }
}

export interface SubTexture {
  name: string;
  x: number;
  y: number;
  width: number;
  height: number;
  frameX: number;
  frameY: number;
  frameWidth: number;
  frameHeight: number;
}